package com.dusk.tool
{
	public class Time
	{
		private var _hour:uint;
		private var _min:uint;
		private var _second:uint;
		private var _totalSecond:uint;
		
		public function Time(second:uint = 0)
		{
			updateFromSecond(second);
		}
		
		public function get hour():uint
		{
			return _hour;
		}
		
		public function set hour(num:uint):void
		{
			var total:uint = num * 3600 + _min * 60 + _second;
			updateFromSecond(total);
		}
		
		public function get min():uint
		{
			return _min;
		}
		
		public function set min(num:uint):void
		{
			var total:uint = _hour * 3600 + num * 60 + _second;
			updateFromSecond(total);
		}
		
		public function get second():uint
		{
			return _second;
		}
		
		public function set second(num:uint):void
		{
			var total:uint = _hour * 3600 + _min * 60 + num;
			updateFromSecond(total);
		}
		
		public function get totalSecond():uint
		{
			return _totalSecond;
		}
		
		public function updateFromSecond(num:uint):void
		{
			_totalSecond = num;
			_hour = Math.floor(num / 3600);
			num %= 3600;
			_min = Math.floor(num / 60);
			num %= 60;
			_second = num % 60;
		}
		
		public function updateFromMilisecond(num:uint):void
		{
			updateFromSecond(num / 1000);
		}
		
		public function updateFromTimeString(str:String):void
		{
			var arr:Array = str.split(":");
			if(!arr.length == 3)
			{
				throw new Error("invalid time string format");
			}
			updateFromSecond(int(arr[0]) * 3600 + int(arr[1]) * 60 + int(arr[2]));
		}
		
		public function add(target:Time):void
		{
			updateFromSecond(_totalSecond + target.totalSecond);
		}
		
		public function addHour(num:int):void
		{
			var sec:int = num * 3600;
			if(sec + _totalSecond < 0)
			{
				throw new Error("invalid input, out of range");
			}
			updateFromSecond(sec + _totalSecond);
		}
		
		public function addMinute(num:int):void
		{
			var sec:int = num * 60;
			if(sec + _totalSecond < 0)
			{
				throw new Error("invalid input, out of range");
			}
			updateFromSecond(sec + _totalSecond);
		}
		
		public function addSecond(num:int):void
		{
			if(num + _totalSecond < 0)
			{
				throw new Error("invalid input, out of range");
			}
			updateFromSecond(num + _totalSecond);
		}
		
		public function toTimeString():String
		{
			return _hour.toString() + ":" + completeZeroFormat(_min) + ":" + completeZeroFormat(_second);
		}
		
		public function toCNTime():String
		{
			return _hour.toString() + "时" + completeZeroFormat(_min) + "分" + completeZeroFormat(_second) + "秒";
		}
		
		private function completeZeroFormat(num:uint):String
		{
			if(num < 10)
			{
				return "0" + num.toString();
			}
			return num.toString();
		}
	}
}
